package com.cheng.student.controller.filter;

import org.apache.ibatis.io.Resources;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@WebFilter(filterName = "Filter1",urlPatterns = {"*.html","/teacher/*","/super/*"})
public class LoginFilter
        implements Filter
{
    public static void main(String args[])
    {

    }
    public void init(FilterConfig config)
            throws ServletException
    {
    }

    public void destroy()
    {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        //登录校验
        HttpServletRequest request1 = (HttpServletRequest)request;

        if(request1.getSession().getAttribute("power") != null)
        {
            request1.getSession().setMaxInactiveInterval(300);
            chain.doFilter(request,response);
        }
        else
        {
            //获取不拦截列表
            InputStream resourceAsStream = Resources.getResourceAsStream("passHtmls.properties");
            Properties properties = new Properties();

            properties.load(resourceAsStream);
            List<String> passHtmls = new ArrayList<>();

            for (int i = 0;properties.getProperty("Html" + i) != null ;i++)
            {
                passHtmls.add(properties.getProperty("Html" + i));
            }

            String uri = request1.getRequestURI();

            //后面没东西就放行
            String[] split = uri.split("/");
            if (split.length == 0)
            {
                chain.doFilter(request, response);
                return;
            }

            //根据放行列表判断是否放行
            boolean isDoFilter = false;
            for (String passHtml:passHtmls)
            {
                if (split[1].equals(passHtml))
                {
                    isDoFilter = true;
                }

            }
            if (isDoFilter)
            {
                chain.doFilter(request,response);
            }
            else
            {
                ((HttpServletResponse)response).sendRedirect("/index.html");
            }

        }
        return;
    }
}
